<template>
  <view class="container">
    <!-- 第一部分：患者信息 -->
    <view class="section patient-info-section">
      <view class="section-header" @click="patientInfoCollapsed = !patientInfoCollapsed">
        <text class="section-title">{{ t('medical.consent_form') }}</text>
        <view class="header-actions">
          <button class="member-btn" @click.stop="gotoMemberSelect">{{ t('medical.choose_member') }}</button>
          <text class="collapse-arrow">{{ patientInfoCollapsed ? '▼' : '▲' }}</text>
        </view>
      </view>
      
      <view v-show="!patientInfoCollapsed" class="section-content">
        <view class="info-form">
          <!-- 用户名 -->
          <view class="form-row">
            <view class="form-label">{{ t('settings.username') }}</view>
            <input v-model="memberForm.username" class="form-input" :placeholder="t('settings.username')" />
          </view>
          
          <!-- 姓 -->
          <view class="form-row">
            <view class="form-label">{{ t('settings.last_name') }}</view>
            <input v-model="memberForm.last_name" class="form-input" :placeholder="t('settings.enter_last_name')" />
          </view>
          
          <!-- 名 -->
          <view class="form-row">
            <view class="form-label">{{ t('settings.first_name') }}</view>
            <input v-model="memberForm.first_name" class="form-input" :placeholder="t('settings.enter_first_name')" />
          </view>
          
          <!-- 出生日期 -->
          <view class="form-row">
            <view class="form-label">{{ t('settings.birthday') }}</view>
            <picker mode="date" :value="memberForm.date_of_birth" @change="onDateChange">
              <view class="form-picker">
                <text>{{ memberForm.date_of_birth || t('settings.select_birthday') }}</text>
                <text class="arrow">▼</text>
              </view>
            </picker>
          </view>

          <!-- 联系电话 -->
          <view class="form-row">
            <view class="form-label">{{ t('settings.mobile') }}</view>
            <input v-model="memberForm.mobile" class="form-input" :placeholder="t('settings.enter_mobile')" />
          </view>
          
          <!-- 性别 -->
          <view class="form-row">
            <view class="form-label">{{ t('settings.gender') }}</view>
            <picker :range="genderOptions" :value="genderIndex" @change="onGenderChange">
              <view class="form-picker">
                <text>{{ getGenderText(memberForm.gender) }}</text>
                <text class="arrow">▼</text>
              </view>
            </picker>
          </view>
          
          <!-- 地址 -->
          <view class="form-row">
            <view class="form-label">{{ t('settings.address') }}</view>
            <textarea v-model="memberForm.address" class="form-textarea" :placeholder="t('settings.enter_address')" />
          </view>
          
          <!-- 医保机构 -->
          <view class="form-row">
            <view class="form-label">{{ t('settings.medical_insurance') }}</view>
            <input v-model="memberForm.medical_insurance" class="form-input" :placeholder="t('settings.enter_medical_insurance')" />
          </view>
          
          <!-- 职业 -->
          <view class="form-row">
            <view class="form-label">{{ t('settings.profession') }}</view>
            <input v-model="memberForm.profession" class="form-input" :placeholder="t('settings.enter_profession')" />
          </view>
          
        </view>
      </view>
    </view>

    <!-- 第二部分：病史记录 -->
    <view class="section medical-history-section">
      <view class="section-header" @click="formCollapsed = !formCollapsed">
        <text class="section-title">{{ t('medical.disease_record_title') }}</text>
        <view class="flex-spacer"></view>
        <text class="collapse-arrow">{{ formCollapsed ? '▼' : '▲' }}</text>
      </view>

      <view v-show="!formCollapsed" class="section-content">
        <!-- 既往病史 - 多选 -->
        <view class="form-row full-width">
          <view class="form-label full-width">{{ t('medical.disease_record') }}</view>
          <view class="multi-select-container">
            <view 
              v-for="item in optionalInfo.select_item" 
              :key="item.id"
              class="multi-select-item"
              :class="{ 'selected': isSelected('disease_record', item.id) }"
              @click="onMultiSelectChange('disease_record', item.id)"
            >
              <text class="item-label">{{ getCurrentLanguage() === 'zh' ? item.label : item.value }}</text>
            </view>
          </view>
          
          <!-- 显示已选择的项目 -->
          <view v-if="formData.disease_record.length > 0" class="selected-items">
            <text class="selected-title">{{ t('medical.selected_items') }}</text>
            <text v-for="(itemId, index) in formData.disease_record" :key="index" class="selected-tag">
              {{ getItemLabel(itemId) }}
            <text class="remove-tag" @click="removeSelectedItem('disease_record', itemId)" :aria-label="t('common.delete')">×</text>
            </text>
          </view>
        </view>
        
        <!-- 选填信息部分 -->
        <view class="form-row full-width">
          <!-- 其他已知疾病 -->
          <view class="optional-form-item">
            <view class="optional-label">{{ t('medical.other_known_diseases') }}</view>
            <textarea 
              v-model="formData.other_known_diseases" 
              class="optional-textarea" 
              :placeholder="t('medical.other_known_diseases_placeholder')"
            />
          </view>
          
          <!-- 既往针灸或干针不良反应 -->
          <view class="optional-form-item">
            <view class="optional-label">{{ t('medical.adverse_reaction') }}</view>
            <textarea 
              v-model="formData.adverse_reaction" 
              class="optional-textarea" 
              :placeholder="t('medical.adverse_reaction_placeholder')"
            />
          </view>
          
          <!-- 过敏史 -->
          <view class="optional-form-item">
            <view class="optional-label">{{ t('medical.allergy_desc') }}</view>
            <textarea 
              v-model="formData.allergy_desc" 
              class="optional-textarea" 
              :placeholder="t('medical.allergy_desc_placeholder')"
            />
          </view>
          
          <!-- 当前用药 -->
          <view class="optional-form-item">
            <view class="optional-label">{{ t('medical.medication_desc') }}</view>
            <textarea 
              v-model="formData.medication_desc" 
              class="optional-textarea" 
              :placeholder="t('medical.medication_desc_placeholder')"
            />
          </view>
        </view>
      </view>
    </view>

    <!-- 第三部分：当前病情 -->
    <view class="section current-condition-section">
      <view class="section-header" @click="currentConditionCollapsed = !currentConditionCollapsed">
        <text class="section-title">{{ t('medical.current_condition') }}</text>
        <view class="flex-spacer"></view>
        <text class="collapse-arrow">{{ currentConditionCollapsed ? '▼' : '▲' }}</text>
      </view>
      
      <view v-show="!currentConditionCollapsed" class="section-content">
        <!-- 主诉症状 -->
        <view class="write-form-item">
          <view class="write-label">{{ t('medical.main_complaint') }}</view>
          <textarea 
            v-model="formData.main_complaint" 
            class="write-textarea" 
            :placeholder="t('medical.main_complaint_placeholder')"
          />
        </view>

        <!-- 疼痛描述 -->
        <view class="write-form-item">
          <view class="write-label">{{ t('medical.pain_description') }}</view>
          <view class="pain-description-container">
            <view 
              v-for="item in optionalInfo.pain_description" 
              :key="item.id"
              class="pain-description-item"
              :class="{ 'selected': isPainDescriptionSelected(item.id) }"
              @click="onPainDescriptionChange(item.id)"
            >
              <text class="pain-item-label">{{ getCurrentLanguage() === 'zh' ? item.label : item.value }}</text>
            </view>
          </view>
          
          <!-- 显示已选择的疼痛描述 -->
          <view v-if="formData.pain_description" class="selected-pain-items">
            <text class="selected-title">{{ t('medical.selected_pain_description') }}</text>
            <text class="selected-tag">
              {{ getPainDescriptionLabel(formData.pain_description) }}
              <text class="remove-tag" @click="removePainDescriptionItem()" :aria-label="t('common.delete')">×</text>
            </text>
          </view>
        </view>

        <!-- 疼痛强度 -->
        <view class="write-form-item">
          <view class="write-label">{{ t('medical.pain_intensity') }}</view>
          <view class="pain-intensity-container">
            <view class="intensity-options">
              <view 
                v-for="intensity in 11" 
                :key="intensity - 1"
                class="intensity-option"
                :class="{ 'selected': formData.pain_intensity === (intensity - 1) }"
                @click="onPainIntensityChange(intensity - 1)"
              >
                <text class="intensity-number">{{ intensity - 1 }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 既往治疗史 -->
        <view class="write-form-item">
          <view class="write-label">{{ t('medical.past_treatment') }}</view>
          <textarea 
            v-model="formData.past_treatment" 
            class="write-textarea" 
            :placeholder="t('medical.past_treatment_placeholder')"
          />
        </view>

        <!-- 伴随症状/体征 -->
        <view class="write-form-item">
          <view class="write-label">{{ t('medical.accompany_symptom') }}</view>
          <textarea 
            v-model="formData.accompany_symptom" 
            class="write-textarea" 
            :placeholder="t('medical.accompany_symptom_placeholder')"
          />
        </view>
        
      </view>
    </view>

    <!-- 第四部分：患者同意声明 -->
    <view class="section consent-declaration-section">
      <view class="section-header" @click="consentDeclarationCollapsed = !consentDeclarationCollapsed">
        <text class="section-title">{{ t('medical.consent_declaration') }}</text>
        <view class="flex-spacer"></view>
        <text class="collapse-arrow">{{ consentDeclarationCollapsed ? '▼' : '▲' }}</text>
      </view>
      
      <view v-show="!consentDeclarationCollapsed" class="section-content">
        <!-- 同意声明内容 -->
        <view class="consent-content">
          <text class="consent-text">{{ t('medical.consent_declaration_text') }}</text>
        </view>
        
        <!-- 患者信息 -->
        <view class="signature-section">
          <view class="signature-row">
            <view class="signature-label">{{ t('medical.patient_name') }}</view>
            <view class="signature-value">{{ getPatientFullName() }}</view>
          </view>
          
          <view class="signature-row">
            <view class="signature-label">{{ t('medical.patient_signature') }}</view>
            <view class="signature-display">
              <image 
                v-if="memberInfo.signature_url" 
                :src="memberInfo.signature_url" 
                class="signature-image" 
                mode="aspectFit"
              />
              <text v-else class="no-signature">{{ t('medical.no_signature') }}</text>
            </view>
            <button class="re-sign-btn" @click="gotoPatientSign">{{ t('medical.re_sign') }}</button>
          </view>
          
          <view class="signature-row">
            <view class="signature-label">{{ t('medical.patient_date') }}</view>
            <view class="signature-value">{{ getCurrentDate() }}</view>
          </view>
        </view>
        
        <!-- 治疗师信息 -->
        <view class="signature-section">
          <view class="signature-row">
            <view class="signature-label">{{ t('medical.therapist_name') }}</view>
            <view class="signature-value">{{ getTherapistName() }}</view>
          </view>
          
          <view class="signature-row">
            <view class="signature-label">{{ t('medical.therapist_signature') }}</view>
            <view class="signature-display">
              <image 
                v-if="therapistSignature" 
                :src="therapistSignature" 
                class="signature-image" 
                mode="aspectFit"
              />
              <text v-else class="no-signature">{{ t('medical.no_signature') }}</text>
            </view>
            <button class="re-sign-btn" @click="gotoTherapistSign">{{ t('medical.re_sign') }}</button>
          </view>
          
          <view class="signature-row">
            <view class="signature-label">{{ t('medical.therapist_date') }}</view>
            <view class="signature-value">{{ getCurrentDate() }}</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 固定底部提交按钮 -->
    <view class="fixed-bottom-btn">
      <button class="fill-btn" @click="submitForm">{{ t('medical.submit_consent') }}</button>
    </view>
  </view>
</template>

<script>
import { useI18n } from 'vue-i18n'
import { getOptionalInfo } from '@/api/medical.js'
import { useUserStore } from '@/store/user.js'
import { resetSignature, uploadSignature } from '@/api/user.js'

export default {
  data() {
    return {
        formCollapsed: false,
        patientInfoCollapsed: false, // 患者信息折叠状态
        currentConditionCollapsed: false, // 当前病情折叠状态
        consentDeclarationCollapsed: false, // 患者同意声明折叠状态
        memberInfo: {}, // 会员信息
        therapistSignature: '', // 治疗师签名图片URL
        memberForm: {
            username: '',
            first_name: '',
            last_name: '',
            date_of_birth: '',
            gender: '',
            address: '',
            medical_insurance: '',
            profession: '',
            mobile: '',
            signature: '',
        },
        formData: {
            patient_id: '',         // 患者ID
            // 病史记录字段
            disease_record: [],    // 既往病史 - 多选
            // 选填信息字段
            other_known_diseases: '',   // 其他已知疾病
            adverse_reaction: '', // 既往针灸或干针不良反应
            allergy_desc: '',   // 过敏史详情
            medication_desc: '',  // 当前用药
            // 当前病情字段
            main_complaint: '',    // 主诉症状
            past_treatment: '', // 既往治疗史
            accompany_symptom: '', // 伴随症状/体征
            pain_description: '',   // 疼痛描述 - 单选
            pain_intensity: 0      // 疼痛强度 - 单选，0-10
       },
       // 可选信息数据
        optionalInfo: {
            select_item: [], // 需要用户选择的项目
            optional_item: [], // 可选项目
            write_item: [], // 需要书写的项目
            pain_description: [] // 疼痛描述
        },
        saving: false,
    }
  },
  setup() {
    const { t } = useI18n()
    const userStore = useUserStore()
    
    // 动态设置页面标题以支持国际化
    if (typeof uni !== 'undefined' && uni.setNavigationBarTitle) {
      uni.setNavigationBarTitle({
        title: t('medical.title')
      })
    }
    return { t, userStore }
  },
  onReady() {
    // 进入页面时设置国际化标题
    if (typeof this.t === 'function') {
      uni.setNavigationBarTitle({
        title: this.t('medical.title')
      })
    }
  },

  computed: {
    userStore() {
      return useUserStore()
    },
    userInfo() {
      return this.userStore.userInfo
    },
    genderOptions() {
      return [
        this.t('settings.male'),
        this.t('settings.female')
      ]
    },
    genderIndex() {
      const gender = this.memberForm.gender
      return gender === 1 ? 0 : 1
    }
  },
  mounted() {
    if (this.userInfo && this.userInfo.signature) {
      this.therapistSignature = this.userInfo.signature;
    }
  },
  onShow() {
    // 设置页面标题
    if (typeof this.t === 'function') {
      uni.setNavigationBarTitle({
        title: this.t('medical.title')
      })
    }
    
    // 监听会员选择事件
    uni.$once('memberSelected', (member) => {
      this.memberInfo = member;
      this.formData.patient_id = member.id;
      this.initMemberForm();
    });
    
    // 会员选择兜底 - 从本地存储恢复数据
    const memberKey = 'helper_selected_member';
    const localMember = uni.getStorageSync(memberKey);
    if (localMember && typeof localMember === 'object') {
      this.memberInfo = localMember;
      this.formData.patient_id = localMember.id;
      this.initMemberForm();
      uni.removeStorageSync(memberKey);
    }
    
    // 获取可选信息
    this.loadOptionalInfo();
    
    // 加载治疗师签名
    this.loadTherapistSignature();
  },

  methods: {


    // 获取性别文本
    getGenderText(gender) {
      if (gender === 1 || gender === 'male') {
        return this.t('settings.male');
      } else if (gender === 0 || gender === 'female') {
        return this.t('settings.female');
      } else {
        return this.t('settings.not_set');
      }
    },

    // 提交表单
    async submitForm() {
      // 验证用户信息
      if (!this.memberForm.last_name.trim()) {
        uni.showToast({ 
          title: this.t('settings.enter_last_name'), 
          icon: 'error' 
        });
        return;
      }

      if (!this.memberForm.first_name.trim()) {
        uni.showToast({ 
          title: this.t('settings.enter_first_name'), 
          icon: 'error' 
        });
        return;
      }

      if (!this.memberForm.mobile.trim()) {
        uni.showToast({ 
          title: this.t('settings.enter_mobile'), 
          icon: 'error' 
        });
        return;
      }

      // 准备完整的医疗记录数据
      const medicalRecordData = {
        ...this.formData,
        patient_info:{
            ...this.memberForm,
        },
        doctor_id: this.userInfo.id,
        doctor_signature: this.userInfo.signature_path,
        signature_date: this.getCurrentDate()
      };

      console.log('提交医疗记录数据:', medicalRecordData);

      // 这里可以调用API保存数据
      // const res = await saveMedicalRecord(medicalRecordData);
      
      uni.showToast({
        title: this.t('medical.save_success'), 
        icon: 'success' 
      });

      // 保存成功后清空缓存并跳转到订单页面
      setTimeout(() => {
        // 跳转到订单页面，携带患者信息参数
        const patientInfo = {
          patient_id: this.memberInfo.id,
          patient_info: {
            ...this.memberForm
          }
        };
        console.log("patientInfo", patientInfo);
        // 将患者信息存储到本地，供order页面使用
        uni.setStorageSync('medical_patient_info', patientInfo);
        
        // 清空本地存储的会员信息
        uni.removeStorageSync('helper_selected_member');
        
        uni.navigateTo({
          url: '/pages/order/index?from=medical'
        });
        
        // 跳转后再清空表单
        this.resetForm();
      }, 1500);
    },

               // 重置表单
      resetForm() {
        this.formData = {
            patient_id: '',
            // 病史记录字段
            disease_record: [],
            // 选填信息字段
            other_known_diseases: '',
            adverse_reaction: '',
            allergy_desc: '',
            medication_desc: '',
            // 当前病情字段
            main_complaint: '',
            past_treatment: '',
            accompany_symptom: '',
            pain_description: '',
            pain_intensity: 0
        };
      
             // 重置用户信息表单
       this.memberForm = {
         username: '',
         first_name: '',
         last_name: '',
         date_of_birth: '',
         gender: '',
         address: '',
         medical_insurance: '',
         profession: '',
         mobile: '',
         signature: ''
       };
      
      // 清空会员信息
      this.memberInfo = {};
    },

    // 跳转到会员选择页面
    gotoMemberSelect() {
      const storageKey = 'helper_selected_member';
      uni.removeStorageSync(storageKey);
      uni.navigateTo({
        url: '/pages/order/member-select',
        events: {
          memberSelected: (member) => {
            this.memberInfo = member;
            this.formData.patient_id = member.id;
            this.initMemberForm();
            uni.removeStorageSync(storageKey);
          }
        }
      });
    },

    // 初始化用户表单
    initMemberForm() {
      if (this.memberInfo.id) {
        this.memberForm = {
          username: this.memberInfo.username || this.memberInfo.name || '',
          first_name: this.memberInfo.first_name || '',
          last_name: this.memberInfo.last_name || '',
          date_of_birth: this.memberInfo.date_of_birth || '',
          gender: this.memberInfo.gender || '',
          address: this.memberInfo.address || '',
          medical_insurance: this.memberInfo.medical_insurance || '',
          profession: this.memberInfo.profession || '',
          mobile: this.memberInfo.mobile || this.memberInfo.member || '',
          signature: this.memberInfo.signature || ''
        };
      }
    },



    // 日期选择处理
    onDateChange(e) {
      this.memberForm.date_of_birth = e.detail.value;
    },

    // 性别选择处理
    onGenderChange(e) {
      this.memberForm.gender = e.detail.value === 0 ? 1 : 0;
    },

    // 保存用户信息
    async saveMemberInfo() {
      if (!this.memberInfo.id) {
        uni.showToast({
          title: this.t('medical.select_member_first'),
          icon: 'error'
        });
        return;
      }

      try {
        this.saving = true;
        
        // 准备API请求数据
        const apiData = {
          ...this.memberForm,
          user_id: this.memberInfo.id
        };

        // 调用API更新用户信息
        const response = await this.userStore.updateUserInfo(apiData);
        
        if (response) {
          // 更新本地会员信息
          this.memberInfo = {
            ...this.memberInfo,
            ...this.memberForm
          };
          
          uni.showToast({
            title: this.t('settings.update_success'),
            icon: 'success'
          });
        }
      } catch (error) {
        console.error('保存用户信息失败:', error);
        uni.showToast({
          title: this.t('settings.update_failed'),
          icon: 'error'
        });
      } finally {
        this.saving = false;
      }
    },


     
     // 加载可选信息
     async loadOptionalInfo() {
       try {
         const response = await getOptionalInfo();
         if (response && response.result) {
           this.optionalInfo = response.result;
         }
       } catch (error) {
         console.error('获取可选信息失败:', error);
       }
     },
     
     // 处理多选变化
     onMultiSelectChange(field, value) {
       if (this.formData[field].includes(value)) {
         // 如果已选中，则移除
         this.formData[field] = this.formData[field].filter(item => item !== value);
       } else {
         // 如果未选中，则添加
         this.formData[field].push(value);
       }
     },
     
     // 检查是否选中
     isSelected(field, value) {
       return this.formData[field].includes(value);
     },
     
     // 根据ID获取项目标签
     getItemLabel(itemId) {
       const item = this.optionalInfo.select_item.find(item => item.id === itemId);
       return item ? item.label : '';
     },
     
     // 移除已选择的项目
     removeSelectedItem(field, itemId) {
       this.formData[field] = this.formData[field].filter(id => id !== itemId);
     },
     
           // 获取当前语言
      getCurrentLanguage() {
        return this.$i18n.locale || 'zh';
      },

      // 疼痛描述相关方法
      onPainDescriptionChange(itemId) {
        // 单选逻辑：如果点击的是已选中的，则取消选择；否则选择新的
        if (this.formData.pain_description === itemId) {
          this.formData.pain_description = '';
        } else {
          this.formData.pain_description = itemId;
        }
      },

      isPainDescriptionSelected(itemId) {
        return this.formData.pain_description === itemId;
      },

      getPainDescriptionLabel(itemId) {
        const item = this.optionalInfo.pain_description.find(item => item.id === itemId);
        return item ? (this.getCurrentLanguage() === 'zh' ? item.label : item.value) : '';
      },

      removePainDescriptionItem() {
        this.formData.pain_description = '';
      },

                           // 疼痛强度相关方法
        onPainIntensityChange(intensity) {
          this.formData.pain_intensity = intensity;
        },

        // 获取患者全名
        getPatientFullName() {
          if (this.memberInfo.first_name && this.memberInfo.last_name) {
            return `${this.memberInfo.last_name}${this.memberInfo.first_name}`;
          } else if (this.memberInfo.username) {
            return this.memberInfo.username;
          } else {
            return this.t('medical.not_filled');
          }
        },

        // 获取当前日期
        getCurrentDate() {
          const now = new Date();
          const year = now.getFullYear();
          const month = String(now.getMonth() + 1).padStart(2, '0');
          const day = String(now.getDate()).padStart(2, '0');
          return `${year}-${month}-${day}`;
        },

                         // 获取治疗师姓名
        getTherapistName() {
          try {
            if (this.userInfo && this.userInfo.first_name && this.userInfo.last_name) {
              return `${this.userInfo.last_name}${this.userInfo.first_name}`;
            } else if (this.userInfo && this.userInfo.username) {
              return this.userInfo.username;
            } else {
              return this.t('medical.not_filled');
            }
          } catch (error) {
            return this.t('medical.not_filled');
          }
        },

                 // 加载治疗师签名
         loadTherapistSignature() {
           try {
             // console.log('userInfo', this.userInfo);
             if (this.userInfo && this.userInfo.signature) {
               this.therapistSignature = this.userInfo.signature;
             }
           } catch (error) {
             console.log('加载治疗师签名失败:', error);
           }
         },

         // 患者重新签名
         gotoPatientSign() {
           // 跳转签名页，签名完成后回传图片
           uni.navigateTo({
             url: '/pages/order/sign',
             events: {
               signImage: (img) => {
                 this.updatePatientSignature(img);
               }
             }
           });
         },

         // 治疗师重新签名
         gotoTherapistSign() {
           // 跳转签名页，签名完成后回传图片
           uni.navigateTo({
             url: '/pages/order/sign',
             events: {
               signImage: (img) => {
                 this.updateTherapistSignature(img);
               }
             }
           });
         },

         // 更新患者签名
         async updatePatientSignature(img) {
           try {
                console.log("this.memberInfo", this.memberInfo)
                if (!this.memberInfo.id) {
                    const res = await uploadSignature({ 
                        signature: img,
                    });
                    if (res.code == 200) {
                        this.memberInfo.signature_url = res.result.url;
                        this.memberForm.signature = res.result.save_path;
                        
                        uni.showToast({ 
                            title: this.t('medical.signature_updated'), 
                            icon: 'success' 
                        });
                    }
                } else {
                    const res = await resetSignature({ 
                        signature: img, 
                        user_id: this.memberInfo.id 
                    });
                    if (res.code == 200) {
                        this.memberInfo.signature_url = res.result.url;
                        this.memberForm.signature = res.result.save_path;
                        
                        uni.showToast({ 
                            title: this.t('medical.signature_updated'), 
                            icon: 'success' 
                        });
                    }
                }
             
           } catch (error) {
             console.error('更新患者签名失败:', error);
             uni.showToast({ 
               title: this.t('common.update_failed'), 
               icon: 'error' 
             });
           }
         },

         // 更新治疗师签名
         async updateTherapistSignature(img) {
           try {
             const res = await resetSignature({ 
               signature: img, 
               user_id: this.userInfo.id 
             });
             if (res.code == 200) {
               // 更新治疗师签名
               this.therapistSignature = res.result.url;
               // 更新本地存储的用户信息
               if (this.userInfo) {
                 this.userInfo.signature = res.result.url;
                 this.userInfo.signature_path = res.result.save_path;
                 this.userInfo.signFile = res.result.url;
                 uni.setStorageSync('userInfo', this.userInfo);
               }
               uni.showToast({ 
                 title: this.t('medical.signature_updated'), 
                 icon: 'success' 
               });
             }
           } catch (error) {
             console.error('更新治疗师签名失败:', error);
             uni.showToast({ 
               title: this.t('common.update_failed'), 
               icon: 'error' 
             });
           }
         },
         

  }
}
</script>

<style scoped>
.container {
  background: #fff;
  min-height: 100vh;
  padding-bottom: 140rpx;
  overflow-x: hidden;
  box-sizing: border-box;
}

.section {
  background: #fafafa;
  margin: 24rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx #eee;
  padding: 24rpx;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  max-width: calc(100% - 48rpx);
  box-sizing: border-box;
  overflow: hidden;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
  cursor: pointer;
  user-select: none;
}

.section-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #1976d2;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.member-btn {
  background: #007aff;
  color: #fff;
  border-radius: 6px;
  padding: 0 16px;
  height: 32px;
  line-height: 32px;
  font-size: 14px;
  border: none;
}

.collapse-arrow {
  color: #888;
  font-size: 24rpx;
}

.section-content {
  margin-top: 20rpx;
}

.info-form {
  margin-top: 20rpx;
}

.form-row {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #e3f2fd;
  flex-direction: row;
  margin-bottom: 16rpx;
}

.form-row.full-width {
  flex-direction: column;
  align-items: flex-start;
  width: 100%;
  min-width: 100%;
}

.form-label {
  font-size: 28rpx;
  color: #1976d2;
  font-weight: 600;
  min-width: 160rpx;
  margin-right: 24rpx;
  flex-shrink: 0;
}

.form-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  padding: 12rpx 16rpx;
  border: 1rpx solid #bbdefb;
  border-radius: 8rpx;
  background: #fff;
  transition: border-color 0.3s ease;
  min-width: 0;
  height: 60rpx;
  box-sizing: border-box;
}

.form-input:focus {
  border-color: #1976d2;
  outline: none;
}

.form-picker {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12rpx 16rpx;
  border: 1rpx solid #bbdefb;
  border-radius: 8rpx;
  background: #fff;
  font-size: 28rpx;
  color: #333;
  transition: border-color 0.3s ease;
  min-width: 0;
  height: 60rpx;
  box-sizing: border-box;
}

.form-picker .arrow {
  color: #1976d2;
  font-size: 24rpx;
}

.form-actions {
  margin-top: 24rpx;
  padding-top: 16rpx;
  border-top: 1rpx solid #f0f0f0;
}

.save-btn {
  background: #1976d2;
  color: #fff;
  border-radius: 8rpx;
  padding: 16rpx 24rpx;
  font-size: 28rpx;
  border: none;
  width: 100%;
}

.save-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.no-member-tip {
  text-align: center;
  padding: 40rpx 0;
  color: #888;
  font-size: 28rpx;
}

.form-section {
  margin: 0 24rpx 24rpx 24rpx;
  background: #f5f5f5;
  border-radius: 12rpx;
  padding: 16rpx;
  box-sizing: border-box;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

/* 移除旧的form-section样式，使用新的section样式 */

.section-header {
  cursor: pointer;
  user-select: none;
  display: flex;
  align-items: center;
  padding: 12rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.collapse-header {
  cursor: pointer;
  user-select: none;
  display: flex;
  align-items: center;
  padding: 12rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.collapse-arrow {
  margin-left: 12rpx;
  color: #888;
  font-size: 24rpx;
  margin-right: 12rpx;
}

.row-flex {
  flex-direction: row !important;
  align-items: center !important;
  margin-bottom: 12rpx !important;
}

.flex-spacer {
  flex: 1;
}



.form-label.full-width {
  width: 100%;
  font-weight: bold;
  color: #1976d2;
  font-size: 26rpx;
  margin-bottom: 12rpx;
}

.form-textarea {
  flex: 1;
  padding: 12rpx 16rpx;
  border: 1rpx solid #bbdefb;
  border-radius: 8rpx;
  background: #fff;
  font-size: 28rpx;
  color: #333;
  transition: border-color 0.3s ease;
  min-width: 0;
  min-height: 80rpx;
  max-height: 120rpx;
  resize: vertical;
  box-sizing: border-box;
  line-height: 1.4;
}

.form-textarea:focus {
  border-color: #1976d2;
  outline: none;
}

.fixed-bottom-btn {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  padding: 16rpx 24rpx 32rpx 24rpx;
  z-index: 100;
  box-shadow: 0 -2rpx 8rpx #eee;
}

.fill-btn {
  width: 100%;
  background: #1976d2;
  color: #fff;
  border-radius: 8rpx;
  font-size: 30rpx;
  height: 80rpx;
  line-height: 80rpx;
  display: block;
}

/* 多选组件样式 */
.multi-select-container {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200rpx, 1fr));
  gap: 20rpx;
  margin-top: 16rpx;
}

.multi-select-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20rpx 16rpx;
  border: 2rpx solid #e3f2fd;
  border-radius: 12rpx;
  background: #fff;
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: center;
  min-height: 120rpx;
  box-sizing: border-box;
}

.multi-select-item:hover {
  border-color: #bbdefb;
  transform: translateY(-2rpx) scale(1.01);
  box-shadow: 0 6rpx 20rpx rgba(25, 118, 210, 0.15);
}

.multi-select-item.selected {
  border-color: #1976d2;
  background: #e3f2fd;
  color: #1976d2;
  transform: scale(1.02);
  box-shadow: 0 4rpx 16rpx rgba(25, 118, 210, 0.2);
}

.multi-select-item.selected .item-label {
  color: #1976d2;
  font-weight: 700;
}

.multi-select-item.selected .item-value {
  color: #1976d2;
  font-weight: 700;
}

.item-label {
  font-size: 26rpx;
  color: #333;
  font-weight: 600;
  margin-bottom: 12rpx;
  line-height: 1.3;
  text-align: center;
  word-break: break-word;
}

.item-value {
  font-size: 22rpx;
  color: #666;
  font-weight: 500;
  margin-bottom: 8rpx;
  line-height: 1.2;
  text-align: center;
  word-break: break-word;
}

/* 已选择项目样式 */
.selected-items {
  width: 100%;
  margin-top: 16rpx;
  padding: 16rpx;
  background: #f8f9fa;
  border-radius: 8rpx;
  border: 1rpx solid #e9ecef;
}

.selected-title {
  font-size: 24rpx;
  color: #1976d2;
  font-weight: 600;
  margin-right: 16rpx;
}

.selected-tag {
  display: inline-block;
  background: #1976d2;
  color: #fff;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  margin: 8rpx 8rpx 8rpx 0;
  position: relative;
}

.remove-tag {
  margin-left: 8rpx;
  font-weight: bold;
  cursor: pointer;
  padding: 0 4rpx;
}

.remove-tag:hover {
  color: #ffebee;
}

/* 选填信息样式 */
.optional-form-item {
  width: 100%;
  min-width: 100%;
  margin-bottom: 24rpx;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  border: 1rpx solid #e9ecef;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.optional-label {
  font-size: 26rpx;
  color: #1976d2;
  font-weight: 600;
  margin-bottom: 16rpx;
  line-height: 1.4;
}

.optional-textarea {
  width: 100%;
  padding: 16rpx;
  border: 1rpx solid #bbdefb;
  border-radius: 8rpx;
  background: #fff;
  font-size: 26rpx;
  color: #333;
  transition: border-color 0.3s ease;
  min-height: 80rpx;
  max-height: 120rpx;
  resize: vertical;
  box-sizing: border-box;
  line-height: 1.4;
  display: block;
  min-width: 0;
  flex: 1;
}

.optional-textarea:focus {
  border-color: #1976d2;
  outline: none;
}

/* 三个部分的独立样式 */
.current-condition-section {
  /* 确保当前病情部分不会出界 */
  max-width: 100%;
  overflow: hidden;
  box-sizing: border-box;
}

/* 患者同意声明样式 */
.consent-declaration-section {
  /* 确保同意声明部分不会出界 */
  max-width: 100%;
  overflow: hidden;
  box-sizing: border-box;
}

.consent-content {
  width: 100%;
  margin-bottom: 24rpx;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  border: 1rpx solid #e9ecef;
}

.consent-text {
  font-size: 26rpx;
  color: #333;
  line-height: 1.6;
  text-align: justify;
  word-break: break-word;
}

.signature-section {
  width: 100%;
  margin-bottom: 24rpx;
  padding: 20rpx;
  background: #fff;
  border-radius: 12rpx;
  border: 1rpx solid #e9ecef;
}

.signature-row {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
  padding: 12rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.signature-row:last-child {
  margin-bottom: 0;
  border-bottom: none;
}

.signature-label {
  font-size: 28rpx;
  color: #1976d2;
  font-weight: 600;
  min-width: 160rpx;
  margin-right: 24rpx;
  flex-shrink: 0;
}

.signature-value {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  flex: 1;
}

.signature-display {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.signature-image {
  width: 120rpx;
  height: 60rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  background: #fff;
}

.no-signature {
  font-size: 24rpx;
  color: #999;
  font-style: italic;
}

.re-sign-btn {
  background: #1976d2;
  color: #fff;
  border-radius: 8rpx;
  font-size: 24rpx;
  padding: 8rpx 16rpx;
  margin-left: 16rpx;
  height: 48rpx;
  line-height: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  border: none;
  white-space: nowrap;
  flex-shrink: 0;
}

.write-form-item {
  width: 100%;
  margin-bottom: 24rpx;
  padding: 20rpx;
  background: #fff;
  border-radius: 12rpx;
  border: 1rpx solid #e9ecef;
  margin-top: 16rpx;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.write-label {
  font-size: 32rpx;
  color: #1976d2;
  font-weight: 600;
  margin-bottom: 16rpx;
  line-height: 1.4;
}

.write-textarea {
  width: 100%;
  padding: 16rpx;
  border: 1rpx solid #bbdefb;
  border-radius: 8rpx;
  background: #fff;
  font-size: 30rpx;
  color: #333;
  transition: border-color 0.3s ease;
  min-height: 80rpx;
  max-height: 120rpx;
  resize: vertical;
  box-sizing: border-box;
  line-height: 1.4;
  display: block;
  min-width: 0;
  max-width: 100%;
  overflow-wrap: break-word;
  word-wrap: break-word;
}

.write-textarea:focus {
  border-color: #1976d2;
  outline: none;
}

/* 疼痛描述样式 */
.pain-description-container {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150rpx, 1fr));
  gap: 16rpx;
  margin-top: 16rpx;
}

.pain-description-item {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16rpx 12rpx;
  border: 2rpx solid #e3f2fd;
  border-radius: 8rpx;
  background: #fff;
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: center;
  min-height: 80rpx;
  box-sizing: border-box;
}

.pain-description-item:hover {
  border-color: #bbdefb;
  transform: translateY(-2rpx);
  box-shadow: 0 4rpx 12rpx rgba(25, 118, 210, 0.15);
}

.pain-description-item.selected {
  border-color: #1976d2;
  background: #e3f2fd;
  color: #1976d2;
  transform: scale(1.02);
  box-shadow: 0 4rpx 16rpx rgba(25, 118, 210, 0.2);
}

.pain-item-label {
  font-size: 24rpx;
  color: #333;
  font-weight: 600;
  line-height: 1.3;
  text-align: center;
  word-break: break-word;
}

.pain-description-item.selected .pain-item-label {
  color: #1976d2;
  font-weight: 700;
}

.selected-pain-items {
  width: 100%;
  margin-top: 16rpx;
  padding: 16rpx;
  background: #f8f9fa;
  border-radius: 8rpx;
  border: 1rpx solid #e9ecef;
}

/* 疼痛强度样式 */
.pain-intensity-container {
  width: 100%;
  margin-top: 16rpx;
}

.intensity-options {
  display: flex;
  flex-wrap: wrap;
  gap: 8rpx;
  margin-top: 16rpx;
  justify-content: flex-start;
}

.intensity-option {
  display: flex;
  align-items: center;
  justify-content: center;
  width: calc(9.09% - 8rpx);
  min-width: 60rpx;
  padding: 16rpx 8rpx;
  border: 2rpx solid #e3f2fd;
  border-radius: 8rpx;
  background: #fff;
  cursor: pointer;
  transition: all 0.3s ease;
  text-align: center;
  min-height: 60rpx;
  box-sizing: border-box;
  flex-shrink: 0;
  flex-grow: 0;
}

.intensity-option:hover {
  border-color: #bbdefb;
  transform: translateY(-2rpx);
  box-shadow: 0 4rpx 12rpx rgba(25, 118, 210, 0.15);
}

.intensity-option.selected {
  border-color: #1976d2;
  background: #e3f2fd;
  color: #1976d2;
  transform: scale(1.02);
  box-shadow: 0 4rpx 16rpx rgba(25, 118, 210, 0.2);
}

.intensity-option .intensity-number {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.intensity-option.selected .intensity-number {
  color: #1976d2;
  font-weight: 700;
}

/* 响应式布局调整 */
@media screen and (max-width: 750rpx) {
  .multi-select-container {
    grid-template-columns: repeat(2, 1fr);
    gap: 16rpx;
  }
  
  .multi-select-item {
    min-height: 100rpx;
    padding: 16rpx 12rpx;
  }
  
  .item-label {
    font-size: 24rpx;
    margin-bottom: 8rpx;
  }
  
  .item-value {
    font-size: 20rpx;
    margin-bottom: 6rpx;
  }

  .pain-description-container {
    grid-template-columns: repeat(2, 1fr);
    gap: 12rpx;
  }
  
  .pain-description-item {
    min-height: 70rpx;
    padding: 12rpx 8rpx;
  }
  
  .pain-item-label {
    font-size: 22rpx;
  }

  .intensity-options {
    gap: 6rpx;
    justify-content: flex-start;
  }
  
  .intensity-option {
    width: calc(9.09% - 6rpx);
    min-width: 50rpx;
    min-height: 50rpx;
    padding: 12rpx 4rpx;
    flex-grow: 0;
  }
  
  .intensity-option .intensity-number {
    font-size: 24rpx;
  }

  .consent-text {
    font-size: 24rpx;
  }

  .signature-label {
    font-size: 26rpx;
    min-width: 140rpx;
  }

  .signature-value {
    font-size: 26rpx;
  }

  .signature-image {
    width: 100rpx;
    height: 50rpx;
  }

  .re-sign-btn {
    font-size: 22rpx;
    padding: 6rpx 12rpx;
    height: 40rpx;
    line-height: 28rpx;
  }
}

@media screen and (min-width: 751rpx) {
  .multi-select-container {
    grid-template-columns: repeat(3, 1fr);
    gap: 24rpx;
  }
  
  .multi-select-item {
    min-height: 140rpx;
    padding: 24rpx 20rpx;
  }
  
  .item-label {
    font-size: 28rpx;
    margin-bottom: 16rpx;
  }
  
  .item-value {
    font-size: 24rpx;
    margin-bottom: 12rpx;
  }

  .pain-description-container {
    grid-template-columns: repeat(4, 1fr);
    gap: 20rpx;
  }
  
  .pain-description-item {
    min-height: 90rpx;
    padding: 20rpx 16rpx;
  }
  
  .pain-item-label {
    font-size: 26rpx;
  }

  .intensity-options {
    gap: 12rpx;
    justify-content: flex-start;
  }
  
  .intensity-option {
    width: calc(9.09% - 12rpx);
    min-width: 70rpx;
    min-height: 70rpx;
    padding: 20rpx 8rpx;
    flex-grow: 0;
  }
  
  .intensity-option .intensity-number {
    font-size: 32rpx;
  }

  .consent-text {
    font-size: 28rpx;
  }

  .signature-label {
    font-size: 30rpx;
    min-width: 180rpx;
  }

  .signature-value {
    font-size: 30rpx;
  }

  .signature-image {
    width: 140rpx;
    height: 70rpx;
  }

  .re-sign-btn {
    font-size: 26rpx;
    padding: 10rpx 20rpx;
    height: 56rpx;
    line-height: 36rpx;
  }
}
</style>
